package com.im.partchat.base;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.LayoutRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.im.partchat.App;
import com.im.partchat.R;
import com.im.partchat.permission.PermissionListener;
import com.im.partchat.utils.AppManager;
import com.im.partchat.utils.ToastUtils;
import com.im.partchat.widget.NetworkStateView;
import com.im.partchat.widget.XLoadingDialog;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;
import io.rong.imkit.RongIM;
import io.rong.imlib.RongIMClient;

/**
 * Created by fzl on 2017/4/6.
 * VersionCode: 1
 * Desc:BaseActivity
 */

public abstract class BaseActivity extends AppCompatActivity implements IBaseView, Toolbar.OnMenuItemClickListener {
    public  final String TAG=this.getClass().getSimpleName();
    protected Toolbar toolbar;
    private NetworkStateView networkStateView;
    private XLoadingDialog xLoadingDialog;
    private PermissionListener mPermissionListener;
    private static final int CODE_REQUEST_PERMISSION = 1;
    private TextView titleView;
    private ILoadingType.LoadingType loadingType;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(getLayoutId());
        AppManager.getAppManager().addActivity(this);
        ButterKnife.bind(this);
        if (isRegisterEventBus()) {
            EventBus.getDefault().register(this);
        }
        loadingType = initLoadType();
        initView(savedInstanceState);
        initData();
    }

    protected abstract int getLayoutId();
    @SuppressLint("InflateParams")
    @Override
    public void setContentView(@LayoutRes int layoutResID) {
        View view = getLayoutInflater().inflate(R.layout.activity_base, null);
        super.setContentView(view);
        if (Build.VERSION.SDK_INT == Build.VERSION_CODES.KITKAT) {
            view.setFitsSystemWindows(true);
        }
        initDefaultView(layoutResID);
    }
    protected ILoadingType.LoadingType initLoadType() {
        return ILoadingType.LoadingType.LOADING_TYPE_DIALOG;
    }
    /**
     * 初始化默认布局的View
     * @param layoutResId 子View的布局id
     */
    private void initDefaultView(int layoutResId) {
        networkStateView = (NetworkStateView) findViewById(R.id.nsv_state_view);
        initToolbar();
        FrameLayout container = (FrameLayout) findViewById(R.id.fl_activity_child_container);
        View childView = LayoutInflater.from(this).inflate(layoutResId, null);
        container.addView(childView, 0);
    }
    protected void initToolbar(){
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        titleView = (TextView) findViewById(R.id.title);
        if (toolbar == null)
            return;
        if (hasToolBar()) {
            if (getSupportActionBar() == null) {
                setSupportActionBar(toolbar);
                toolbar.setNavigationIcon(R.drawable.rc_ac_file_preview);
                toolbar.setNavigationOnClickListener(OnToolbarNavigation());
                toolbar.setOnMenuItemClickListener(this);
            }

        }else {
            toolbar.setVisibility(View.GONE);
        }

    }
    protected  void  setToolbarTitle(String title){
        if (titleView==null){
            titleView = (TextView) findViewById(R.id.title);
        }
        toolbar.setTitle("");
        titleView.setText(title);
    }

    protected  void  setToolbarTitleVisable(boolean isVisable){
        if (titleView==null){
            titleView = (TextView) findViewById(R.id.title);
        }

        titleView.setVisibility(isVisable?View.VISIBLE:View.GONE);
    }

    protected void initView(@Nullable Bundle savedInstanceState) {
    }

    protected abstract void initData();

    @NonNull
    private View.OnClickListener OnToolbarNavigation() {
        return new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onToolBarNavigationClick();

            }
        };
    }

    protected  void onToolBarNavigationClick(){
        finish();
    }

    public void showToast(String msg) {
        ToastUtils.showShort(msg);
    }

    @Override
    public void showEmpty() {
        networkStateView.showEmpty();

    }

    public void showPageSuccess() {
        networkStateView.showSuccess();
    }

    @Override
    public void showLoading(String msg) {
        if (loadingType == ILoadingType.LoadingType.LOADING_TYPE_DIALOG) {
            if (xLoadingDialog == null) {
                xLoadingDialog = new XLoadingDialog(this);
                xLoadingDialog.setCanceled(false);
                xLoadingDialog.setMessage(msg);
                xLoadingDialog.show();
            } else {
                xLoadingDialog.setMessage(msg);
                xLoadingDialog.show();
            }
        }else {
            networkStateView.showLoading();
        }
    }


    @Override
    public void hideLoading() {
        if (loadingType == ILoadingType.LoadingType.LOADING_TYPE_DIALOG) {
            if (xLoadingDialog != null) {
                xLoadingDialog.dismiss();
            }
        }else {
            networkStateView.showSuccess();
        }
    }

    @Override
    public void showError(String error) {
        showToast(error);

    }

    @Override
    public boolean onMenuItemClick(MenuItem item) {
        return false;
    }

    protected boolean isRegisterEventBus() {
        return false;
    }

    @Override
    protected void onDestroy() {
        if (isRegisterEventBus()) {
            EventBus.getDefault().unregister(this);
        }        AppManager.getAppManager().removeActivity(this);

        super.onDestroy();
    }

    public  void requestPermissions(String[] permissions, PermissionListener listener) {
        Activity activity = AppManager.getAppManager().currentActivity();
        if (null == activity) {
            return;
        }

        mPermissionListener = listener;
        List<String> permissionList = new ArrayList<>();
        for (String permission : permissions) {
            //权限没有授权
            if (ContextCompat.checkSelfPermission(activity, permission) != PackageManager.PERMISSION_GRANTED) {
                permissionList.add(permission);
            }
        }

        if (!permissionList.isEmpty()) {
            ActivityCompat.requestPermissions(activity, permissionList.toArray(new String[permissionList.size()]), CODE_REQUEST_PERMISSION);
        } else {
            mPermissionListener.onGranted();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case CODE_REQUEST_PERMISSION:
                if (grantResults.length > 0) {
                    List<String> deniedPermissions = new ArrayList<>();
                    for (int i = 0; i < grantResults.length; i++) {
                        int result = grantResults[i];
                        if (result != PackageManager.PERMISSION_GRANTED) {
                            String permission = permissions[i];
                            deniedPermissions.add(permission);
                        }
                    }

                    if (deniedPermissions.isEmpty()) {
                        mPermissionListener.onGranted();
                    } else {
                        mPermissionListener.onDenied(deniedPermissions);
                    }
                }
                break;

            default:
                break;
        }
    }


    protected void connect(String token ,RongIMClient.ConnectCallback callBack) {

        if (getApplicationInfo().packageName.equals(App.getCurProcessName(getApplicationContext()))) {
            RongIM.connect(token, callBack);
        }
    }
    protected boolean hasToolBar(){
        return true;
    }
}
